package servlet;

import bean.Result;
import biz.BizException;
import biz.ProductBiz;
import com.google.gson.Gson;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "SaveProductServlet", value = "/SaveProductServlet.s")
public class SaveProductServlet extends HttpServlet {

    private ProductBiz biz = new ProductBiz();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");

        final String proname = request.getParameter("proname");
        final String num = request.getParameter("num");
        final String tname = request.getParameter("tname");
        final String price = request.getParameter("price");
        final String image = request.getParameter("image");
        final String message = request.getParameter("message");
        final String recommend = request.getParameter("recommend");
        final String proid = request.getParameter("proid");

        Result result =null;

        try{
            if(proid == null || "".equals(proid)){
                biz.saveProduct(proname, num, tname, price, image, message,recommend);
            } else {
                biz.modifyProduct(proid, proname, num, tname, price, image, message,recommend);
            }

            result = new Result(1, "保存成功！", null);
        } catch (BizException e){
            e.printStackTrace();
            result = new Result(0,e.getMessage(), null);
        }catch (Exception e){
            e.printStackTrace(); //打印运行时异常
        }

        final String json = new Gson().toJson(result);
        response.getWriter().append(json);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
